import type { CreateUpdateShopDto, ShopDto } from './models';
import { RestService, Rest } from '@abp/ng.core';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class ShopService {
  apiName = 'Default';
  

  constructor(private restService: RestService) {}

  getList = (input: PagedAndSortedResultRequestDto) => {
    console.log('代理服务调用getList，参数:', input);
    return this.restService.request<any, PagedResultDto<ShopDto>>({
      method: 'GET',
      url: '/api/app/shop',
      params: { 
        skipCount: input.skipCount, 
        maxResultCount: input.maxResultCount, 
        sorting: input.sorting 
      },
    }).pipe(
      tap(response => console.log('代理服务获取商品列表成功:', response)),
      catchError(error => {
        console.error('代理服务获取商品列表失败:', error);
        throw error;
      })
    );
  };

  get = (id: string) => {
    console.log('代理服务调用get，ID:', id);
    const encodedId = encodeURIComponent(id);
    return this.restService.request<any, ShopDto>({
      method: 'GET',
      url: `/api/app/shop/${encodedId}`,
    }).pipe(
      tap(response => console.log('代理服务获取商品详情成功:', response)),
      catchError(error => {
        console.error('代理服务获取商品详情失败:', error);
        throw error;
      })
    );
  };

  create = (input: CreateUpdateShopDto) => {
    console.log('代理服务调用create，数据:', input);
    return this.restService.request<any, ShopDto>({
      method: 'POST',
      url: '/api/app/shop',
      body: input,
    }).pipe(
      tap(response => console.log('代理服务创建商品成功:', response)),
      catchError(error => {
        console.error('代理服务创建商品失败:', error);
        throw error;
      })
    );
  };

  update = (id: string, input: CreateUpdateShopDto) => {
    console.log('代理服务调用update，ID:', id, '数据:', input);
    const encodedId = encodeURIComponent(id);
    return this.restService.request<any, ShopDto>({
      method: 'PUT',
      url: `/api/app/shop/${encodedId}`,
      body: input,
    }).pipe(
      tap(response => console.log('代理服务更新商品成功:', response)),
      catchError(error => {
        console.error('代理服务更新商品失败:', error);
        throw error;
      })
    );
  };

  delete = (id: string) => {
    console.log('代理服务调用delete，ID:', id);
    const encodedId = encodeURIComponent(id);
    return this.restService.request<any, void>({
      method: 'DELETE',
      url: `/api/app/shop/${encodedId}`,
    }).pipe(
      tap(() => console.log('代理服务删除商品成功')),
      catchError(error => {
        console.error('代理服务删除商品失败:', error);
        throw error;
      })
    );
  };
}

export interface PagedAndSortedResultRequestDto {
  skipCount?: number;
  maxResultCount?: number;
  sorting?: string;
}

export interface PagedResultDto<T> {
  items: T[];
  totalCount: number;
} 